package com.chenhy.springbootvuesmbms.api;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

public class DrawCaptcha {
    private static final char[] charList = new char[]{'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y' ,'z',
                                                        'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S' ,'T','U','V','W','X','Y','Z',
                                                        '0','1','2','3','4','5','6','7','8','9'};
    public static String drawRandomCaptcha(int width, int height, BufferedImage verifyImg){
        Graphics2D graphics = (Graphics2D) verifyImg.getGraphics();
        graphics.setColor(Color.WHITE);  //设置画笔颜色-验证码背景色
        graphics.fillRect(0, 0, width, height);  //填充背景
        graphics.setFont(new Font("微软雅黑", Font.BOLD, 40));
        StringBuilder builder = new StringBuilder();
        int x = 10; // 初始字符位置旋转原点
        Random random = new Random();
        for (int i = 0; i < 4; i++) {
            graphics.setColor(getRandomColor());
            int degree = random.nextInt()%40; // 对随机数取余使数字为0到40
            int dot = random.nextInt(charList.length); // 随机选择一个字符的下标
            builder.append(charList[dot]);
            // 画字
            graphics.rotate(degree*Math.PI/180, x, 45);  // 让画笔倾斜
            graphics.drawString(charList[dot]+"", x, 45);  // 画出字符
            graphics.rotate(-degree*Math.PI/180, x, 45); // 把画笔转回来
            x+=48;
        }
        for (int i = 0; i < 20; i++) {
            graphics.setColor(getRandomColor());
            graphics.drawLine(random.nextInt(width), random.nextInt(height),
                    random.nextInt(width), random.nextInt(height));
        }
        for (int i = 0; i < 1000; i++) {
            graphics.setColor(getRandomColor());
            graphics.fillRect(random.nextInt(width), random.nextInt(height), 1, 1);
        }
        for (int i = 0; i < 100; i++) {
            graphics.setColor(getRandomColor());
            graphics.fillRect(random.nextInt(width), random.nextInt(height), 2, 2);
        }
        for (int i = 0; i < 30; i++) {
            graphics.setColor(getRandomColor());
            graphics.drawOval(random.nextInt(width), random.nextInt(height),
                    30, 30);
        }
        return builder.toString();
    }

    private static Color getRandomColor(){
        Random random = new Random();
        return new Color(random.nextInt(256),
                random.nextInt(256),
                random.nextInt(256));
    }
}
